package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class UploadService {

    private static final String IMAGE_DIR = "C:\\lesson\\heima74\\nginx-1.12.2\\html\\images";

    private static final String IMAGE_URL = "http://image.leyou.com/images/";

    private static final List<String> ALLOW_IMAGE_TYPES = Arrays.asList("image/jpeg", "image/png");

    public String uploadImage(MultipartFile file) {

        try {
            // 0.文件校验
            // 0.1.后缀名校验
            String contentType = file.getContentType();
            if (!ALLOW_IMAGE_TYPES.contains(contentType)) {
                throw new RuntimeException("图片格式不正确！");
            }
            // 0.2.内容校验
            try {
                BufferedImage image = ImageIO.read(file.getInputStream());
                if (image == null) {
                    // 图片格式不正确
                    throw new RuntimeException();
                }
            } catch (IOException e) {
                throw new RuntimeException("图片格式不正确！");
            }

            // 1.文件存储路径
            // 获取文件名
            String filename = file.getOriginalFilename();
            // 获取后缀名
            String extension = StringUtils.substringAfterLast(filename, ".");
            // 生成文件名
            filename = UUID.randomUUID().toString() + "." + extension;
            // 创建出文件的存储路径
            File path = new File(IMAGE_DIR, filename);

            // 2.存储文件
            try {
                file.transferTo(path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            // 3.返回图片地址
            return IMAGE_URL + filename;
        } catch (Exception e) {
            log.error("文件上传失败，原因：{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }

    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS client;

    public Map<String, Object> getSignature() {
        try {
            // 1.生成签名
            // 1.1.过期时间
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // 1.2.限制条件
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 1.3.对条件序列号
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            // 1.4.对条件加密
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 1.5.生成签名
            String postSignature = client.calculatePostSignature(postPolicy);

            // 2.准备返回值结果
            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
